package com.test.tool.demo.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author 小八
 * @date 2022年04月26日9:28
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SocketMessageHandler {

    private final SimpMessagingTemplate template;

    private final AynscPushMsgHandler aynscPushMsgHandler;

    /**
     * 分布式分发消息
     *
     * @param channel     通道
     * @param messageJson 消息内容
     * @param message     消息体
     */
    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(),
        exchange = @Exchange(value = RabbitMqConfig.SOCKET_MSG_EXCHANGE, type = "fanout"),
        key = ""
    ))
    public void msgHandler(Channel channel, String messageJson, Message message) {
        try {
            WebSocketMsgVO webSocketMsgVO = JSONUtil.toBean(messageJson, WebSocketMsgVO.class);
            String sendMsg = JSONUtil.toJsonStr(webSocketMsgVO);
            if (StrUtil.isNotBlank(webSocketMsgVO.getTo())) {
                List<String> users = StrUtil.split(webSocketMsgVO.getTo(), ";");
                //发送到个人  前端 /user/用户名/message 接收
                users.forEach((user)->{
                    aynscPushMsgHandler.ayscnSend(user, sendMsg);
                });
            } else {
                // 发送到多人 前端 /topic/message 接收
                String topicChannel = Optional.ofNullable(webSocketMsgVO.getTopicChannel()).orElse("topic/message");
                template.convertAndSend("/" + topicChannel , sendMsg);
            }
            // 确认消息消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            log.error("收到检测数据异常，错误信息:[{}]", e);
        }
    }

}
